﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_TH_DangNhap : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // get references to the button, checkbox and textboxes
        TextBox usernameTextBox = UserName;
        TextBox passwordTextBox = Password;
        CheckBox persistCheckBox = RememberMe;
        Button loginButton = LoginButton;
        // tie the two textboxes and the checkbox to the button
        Utilities.TieButton(this.Page, usernameTextBox, loginButton);
        Utilities.TieButton(this.Page, passwordTextBox, loginButton);
        Utilities.TieButton(this.Page, persistCheckBox, loginButton);
        // set the page title
        // set focus on the username textbox when the page loads
        usernameTextBox.Focus();
    }

    protected void LoginButton_Click(object sender, EventArgs e)
    {
        if (Membership.ValidateUser(UserName.Text, Password.Text))
        {
            FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
            // Get a reference to the currently logged on user
            MembershipUser currentUser = Membership.GetUser(UserName.Text); 
            // Determine the currently logged on user's UserId value  
            Guid currentUserId = (Guid)currentUser.ProviderUserKey;
            Session.Add("g_UserId", currentUserId);

            //luu thong tin dang nhap vao cookie
            HttpCookie aCookie = new HttpCookie("UserId");
            aCookie.Value = currentUserId.ToString();
            aCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(aCookie);

            //lay roles
            string[] strRole = Roles.GetRolesForUser(UserName.Text);
            Session.Add("RoleForUser", strRole[0]);

            //luu thong tin dang nhap vao cookie
            aCookie = new HttpCookie("RoleForUser");
            aCookie.Value = strRole[0];
            aCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(aCookie);
        }
    }
}
